#!/usr/bin/python3
# 获取全国所有城市的天气数据
import requests

# 基本参数配置

apiKey = 'de361490a11688d82571a50f86ab80bd'  # 在个人中心->我的数据,接口名称上方查看


# 获取城市列表
def get_city_list():
    # 接口请求入参配置
    requestParams = {
        'key': apiKey,
    }
    apiUrl = 'http://apis.juhe.cn/simpleWeather/cityList'  # 接口请求URL
    # 发起接口网络请求
    response = requests.get(apiUrl, params=requestParams)
    responseResult = response.json()
    # 解析数据
    citys = set([line["city"] for line in responseResult['result']])
    return citys


# 获取天气
def get_tq(citys):
    with open("city.txt",mode="w",encoding="utf-8") as f:
        for city in citys:
            print(f"正在获取：{city}")
            # 接口请求入参配置
            requestParams = {
                'key': apiKey,
                'city': city,
            }
            # 发起接口网络请求
            apiUrl = 'http://apis.juhe.cn/simpleWeather/query'  # 接口请求URL
            response = requests.post(apiUrl, params=requestParams)

            responseResult = response.json()
            # 网络请求成功。可依据业务逻辑和接口文档说明自行处理。

            # 解析数据
            for item in responseResult["result"]["future"]:
                date = item["date"]
                temperature = item["temperature"]
                weather = item["weather"]
                direct = item["direct"]

                # 保存到文件
                f.write(f"{city}\t{date}\t{temperature}\t{weather}\t{direct}\n")


# 代码的入口
if __name__ == '__main__':
    # 获取城市列表
    citys = get_city_list()

    # 获取城市天气数据
    get_tq(citys)